package com.yl.chainStore.interceptor

import com.yl.common.clearContext
import com.yl.common.setContext
import com.yl.common.utils.checkTokenAndGetValue
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.servlet.HandlerInterceptor
import java.io.InputStream
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 第一个拦截器
 * 处理\校验token.
 * 配置当前运行时上下文
 * 结束后清理内存数据
 */
class WebContextInterceptor : HandlerInterceptor {
	@Value("\${config.token-key}")
	private lateinit var key: String

	companion object {
		private val log = LoggerFactory.getLogger(WebContextInterceptor::class.java)
	}

	override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {


		val token = request.getHeader("Token")
		if (token != null) {
			try {
				setContext(checkTokenAndGetValue(token, key))
			} catch (e: Exception) {
				log.error("检验token出现异常:{}", e.message)
				response.contentType = "text/html;charset=utf-8"
				response.writer.println("{\"code\":401,\"msg\":\"${e.message}\"}")
				return false
			}
		} else {
			log.error("检验token出现异常:'请传入token'")
			response.contentType = "text/html;charset=utf-8"
			response.writer.println("{\"code\":401,\"msg\":\"token is undefined\"}")
			return false
		}

		return true
	}


	override fun afterCompletion(
		request: HttpServletRequest,
		response: HttpServletResponse,
		handler: Any,
		ex: Exception?
	) {
		//进行清理动作
		clearContext()
	}
}
